<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="500">
    <el-form :model="dialogForm" size="small" :rules="rules" ref="dialogFormRef">
      <el-form-item label="报告名称" prop="docName">
        <el-input v-model="dialogForm.docName" />
      </el-form-item>
      <el-form-item label="机型选择" prop="aircraftType" required>
        <el-select placeholder="请选择机型" style="width:100%;" v-model="dialogForm.aircraftType">
          <el-option v-for="item in aircraftTypes" :label="item" :value="item" :key="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目选择">
        <el-select placeholder="请选择独立分析项目" style="width:100%;" v-model="dialogForm.project" @change="changeProject"
          clearable>
          <el-option v-for="item in independentList" :label="item.projectName" :value="item.projectId"
            :key="item.projectId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择模板" required>
        <el-input v-model="templateInfo.name" disabled />
      </el-form-item>
      <el-form-item label="选择分析" prop="algoCode" required>
        <el-select placeholder="请选择分析" multiple style="width:100%;" @change="algoChange" v-model="dialogForm.algoCode">
          <el-option v-for="item in algos" :label="item.projectName + ' — ' + item.algoName" :value="item.algoCode"
            :key="item.algoCode"></el-option>
        </el-select>
      </el-form-item>
      <div style="color:red;">注：报告生成按照算例选择顺序生成。</div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSure">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getAlgoTree, getReportList, generateReport } from "@/api/computingConfig.js";
import { getDocTree, getTemplateTree, getTemplateList } from "@/api/business";
import qs from "qs";
export default {
  name: "VariableDialog",
  props: {
    datas: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      title: "",
      dialogVisible: true,
      dialogForm: {
        aircraftType: '',
        algoCode: '',
        docName: '',
        templateId: '',
      },
      disabled: false,
      rules: {
        docName: [
          { required: true, message: "请填写报告名称", trigger: 'blur' },
        ],
        algoCode: [
          { required: true, message: "请选择分析", trigger: 'change' },
        ],
        aircraftType: [
          { required: true, message: "请选择机型", trigger: 'change' },
        ],
      },
      // 算例列表
      algos: [],
      queryParams: {
        pageNum: 1,
        pageSize: 100,
      },
      aircraftTypes: ['C909', 'C919', 'C929'],
      templateInfo: {},
      templateId: "",
      //独立分析列表
      independentList: [],
      oraginalAlgos: [],
      chooseAnalysis: []
    };
  },
  mounted() {
    this.initData();
    this.getAlgos();
    this.getTemplate();
    this.getIndependentProject();
  },
  methods: {
    initData() {
      this.dialogForm = {
        id: this.datas.taskId,
        aircraftType: this.datas.aircraftType,
        algoCode: this.datas.algoCode,
        templateId: this.datas.templateId,
        docName: this.datas.docName || this.datas.projectName,
      };
    },
    // 选择项目
    async changeProject(event) {
      this.algos = [...this.oraginalAlgos];
      if (event) {
        const res = await getAlgoTree({
          projectId: event
        });
        if (res?.data) {
          const name = await this.independentList.filter(item => {
            return item.projectId = event;
          })
          res.data.forEach(item => {
            item.projectName = name[0].projectName;
          })
        }
        this.algos = [...this.algos, ...res.data]
      }
    },
    // 选择分析
    algoChange(event) {
      this.chooseAnalysis = [...event];
    },
    // 获取独立分析项目
    getIndependentProject() {
      getReportList({ projectType: 'independent' }).then(res => {
        if (res) {
          this.independentList = res?.data || [];
        }
      });
    },
    // 查询算力列表
    async getAlgos() {
      this.algos = [];
      const res = await getAlgoTree({
        projectId: this.datas.projectId
      });
      if (res?.data) {
        res.data.forEach(item => {
          item.projectName = this.datas.projectName;
        })
      }
      this.oraginalAlgos = res?.data;
      this.algos = this.oraginalAlgos;
    },
    handleClose() {
      this.$emit("on-close");
    },
    // 查询报告模板ID      
    async getTemplate() {
      await getTemplateTree().then(async res => {
        if (res?.data) {
          let algoTemplate = await res?.data[0]?.children.filter(item => {
            return item.name.includes('报告自动生成')
          }) || [];
          let stressTemplateId = algoTemplate[0].id;
          //查询模板文章信息
          await getTemplateList({
            classifyId: stressTemplateId,
            pageNum: 1,
            pageSize: 100
          })
            .then(async (res) => {
              const dataList = await res.data.list.map(i => {
                return {
                  ...i,
                  isPublished: i.status === '1'
                }
              })
              this.templateInfo = { ...dataList[0] };
              this.dialogForm.templateId = this.templateInfo.id;
              this.dialogForm.templateName = this.templateInfo.name;
              this.templateId = dataList[0].id;
            })
        }
      })
    },
    handleSure() {
      this.$refs.dialogFormRef.validate(async (valid) => {
        if (valid) {
          // 先增加文章，再绑定文章ID绑定到静强度报告
          let params = {
            classifyId: null,
            deadlineTime: "2099-12-26T16:00:00.000Z",
            docName: this.dialogForm.docName,
            templateId: null,
            projectId: this.datas.projectId
          }
          let treeNode = [];
          await getDocTree().then(res => {
            if (res) {
              treeNode = res?.data[0]?.children.filter(item => {
                return item.name.includes('静强度报告');
              })

            }
          })
          // 新增文章
          params.classifyId = treeNode[0].id;
          params.templateId = this.templateId;
          params.aircraftType = this.dialogForm.aircraftType;
          // 选择的分析
          let algoResultSelectedList = [];
          let paramsId = [];
          this.chooseAnalysis.forEach(item => {
            this.algos.forEach(el => {
              if (item === el.algoCode) {
                algoResultSelectedList.push({ algoCode: el.algoCode, projectId: el.projectId })
                paramsId.push(el.algoConfigInfo.id);
              }
            })
          })
          params.algoResultSelectedList = [...algoResultSelectedList];
          generateReport(params).then(res => {
            if (res?.data) {
              // 跳转到文章编辑页面
              this.handleClose();
              const query = qs.stringify({
                docNo: res?.data,
                editContentType: "document",
                algos:paramsId.toString(),
                docStatus:9
              });
              window.open(`/editor/view?` + query, "_blank");
              
            }
          })
        } else {
          this.$message.error("信息填写不完整！");
        }
      });
    },
  },
};
</script>

<style scoped>
.card-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-delete {
  cursor: pointer;
}

.card-delete:hover {
  color: #f00;
}
</style>